/*
 *
 */
package br.com.aggjpsv.libraryserver.http;

import br.com.aggjpsv.libraryserver.FactoryAbstract;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;

/**
 *
 * @author Sérgio C. Peres
 * @author Guilherme Alves
 */
public class HTTPServerBasic {

    private FactoryAbstract factory;
    private ExecutorService pool;

    public HTTPServerBasic(FactoryAbstract factory) {
        this.factory = factory;
        pool = this.factory.getPoolThread();
    }
    
    public void run() {
        ServerSocket socketServidor = null;
        System.out.println("Servidor Iniciando...");
        
        try {
            System.out.println("Tentando alocar a porta... [" + factory.getParametros().getPort() + "]");
            socketServidor = new ServerSocket(factory.getParametros().getPort());
        } catch (java.io.IOException e) {
            System.out.println("Erro Fatal: " + e.getMessage());
            return;
        } catch (Exception e) {
            System.out.println("Erro Fatal: " + e.getMessage());
            return;
        }
        
        System.out.println("Servidor OK!");
        
        while (true) {
            System.out.println("Servidor Aguardando...");
            try {
                /**
                 * A factory verifica qual é o tipo de serviso e cria um 
                 * objeto Runnable adequando e passa para o pool.
                 */
                pool.submit(factory.getService(socketServidor.accept()));
            } catch (java.io.IOException ex) {
                System.out.println("Erro de conexão: " + ex.getMessage());
                break;
            }
        }
    }
}
